<?php
class Files{   
	public static function getAllFiles(){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `file`
    ORDER BY `ID_file` DESC";
		return $objDB->select($stmt);
	}
	
	/**
	 * сохраняем файл
	 */
	public static function saveFile($arrFile){
		$objDB = Service_Database::instance();
		$stmt = "
		INSERT INTO `file` (`type`, `name`, `unique_name`, `size`, `creation`, `new_name`)
		VALUES ('" . $arrFile['type'] . "', '" . $arrFile['name'] . "', '" . $arrFile['unique_name'] . "', " . $arrFile['size'] . ", '" . Service_Date::gLocalTime2BD() . "', '" . (empty($arrFile['new_name']) ? $arrFile['name'] : $arrFile['new_name']) . "')";
		$objDB->query($stmt);
	}
  
  
	/**
	 * получаем всю инфу о файле
	 */
	public static function getFileById($idFile){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `file`
		WHERE `file`.`ID_file` = " . $idFile;
		return $objDB->selectOne($stmt);		
	}
  
  /**
	 * удаляем файлы
	 *
	 */
	public static function deleteFiles($arrFiles){
		self::deleteFilesFromFolder($arrFiles['unique_name']);
		self::deleteFilesFromDb($arrFiles['ids']);
		return true;
	}
	
	/**
	 * удаляем файлы с БД
	 *
	 */
	private static function deleteFilesFromDb($arrFilesIds){
		$objDB = Service_Database::instance();
		$stmt = "
		DELETE FROM `file`
		WHERE `file`.`ID_file` IN(" . join($arrFilesIds, ', ') . ")";
		return $objDB->query($stmt);
	}
	
	/**
	 * удаляем файлы из Папки
	 *
	 */
	private static function deleteFilesFromFolder($arrFilesNames){
		foreach ($arrFilesNames as $fileName)
			@unlink(ABSPATH . "content/upload_files/" . $fileName);
	}
}
?>